<!-- 角色选择  -->
<template>
    <div class="departSelect">

        <van-popup v-model:show="showSelectDepart" round position="bottom" :overlay="overlay">
            <van-cascader
            v-model="selectedValue"
            title="请选择接收对象"
            :options="departList"
             :field-names="fieldNames"
            @close="handleClose"
            @change="onChange"
            @finish="onFinish"
        /> 
        </van-popup>
        
    </div>
</template>

<script lang="ts" setup>

interface RoleSelectProp{
    modelValue?:OaWorkflowRole
    workflowId:string
    show:boolean
    overlay:boolean
}

import type { OaWorkflowRole} from '@/types/workflow';
import { onMounted, ref ,watch,defineProps, watchEffect} from 'vue';
import { closeToast, showLoadingToast } from 'vant';
import * as workflowApi from '@/api/workFlowApi'
const selectedValue = ref();
const showSelectDepart = ref(false)


const departList = ref<OaWorkflowRole[]>();

const fieldNames = {
      text: 'roleName',
      value: 'roleId',
      children: 'children',
};


const emiter = defineEmits(["update:modelValue",'update:show'])
const props = defineProps<RoleSelectProp>();

 

watch(()=>props.show,()=>{
    console.log('show changed')
    showSelectDepart.value = props.show;
})

const handleClose = ()=>{
    emiter('update:show',false)
    showSelectDepart.value = false;
}

interface SelectItem{
    selectedOptions:OaWorkflowRole[]
    tabIndex: number
}
    
const onChange = async (param:SelectItem) => {

    const selectedRole = param.selectedOptions[param.tabIndex];
    

    if(selectedRole.grantable){//可授权，无需加载子类型
        return;
    }

    //加载子类型
    showLoadingToast('加载中...');
    const list =  await workflowApi.getChildrenRoles(selectedRole.roleId);
    closeToast();

    if(list && list.length > 0){
        selectedRole.children = list;
    }else{

    }

   
};
    
const onFinish = (param:SelectItem) => {
        handleClose();

        const selectedRole = param.selectedOptions[param.tabIndex];
        emiter('update:modelValue',selectedRole)
  
};

onMounted(()=>{
    initDepartList();
})

 

const initDepartList = async ()=>{
    const roles = await  workflowApi.getTopRoles(1);    
    roles?.forEach((ele)=>{
        if(!ele.grantable){
            ele.children = [];
        }
    })
    departList.value = roles;
 }


 
 
 
    
    
</script>

<style lang="less" scoped>
.departSelect{
    width: 100%;
    .selectDepartTitle{
        text-align: center;
        padding-top: 20px;
        padding-bottom: 4px;
    }
}
</style>